import { requestUrl } from '@/common/config'
import store from '@/common/store'
import md5 from '@/common/api/md5.js'

let user = {
	user_type: 3,
	customer_id: ''
}
function getType(data, method) { // 获取请求方式
	method = method || 'get';
	// method.toUpperCase() === 'POST' && 
	if (data && Object.keys(data).length > 0) {
		const keys = Object.keys(data);
		let filterParams = {};
		let dataArr=[]
		for (let i = 0; i < keys.length; i++) {
			if (data[keys[i]] !== undefined && data[keys[i]] !== null && data[keys[i]] !== '' && !Number.isNaN(data[keys[i]])) {
				filterParams[keys[i]] = data[keys[i]];
			}
			if(keys[i]!='access_token'){
				dataArr.push([keys[i], data[keys[i]]].join('='))
			}
		}
		// console.log(...dataArr)
		let time = Math.round(new Date().getTime() / 1000).toString()
		let Time = ['time', time].join('=')
		// console.log(Time)
		let content = ['content=pinet.FeiMao.2017'].join()
		let arr = [content, ...dataArr, Time].sort(function(a, b) {
			a - b
		})
		let sign = md5(arr.join('&'))
		
		data = filterParams;
		data.sign=sign
		data.time=time
	}
	return {
		method: method,
		data: data,
		header: {
			'content-type': 'application/x-www-form-urlencoded',
			'Authorization': store.state.token
		},
	}
}

function Request(url, method, data, loading) {
	// #ifdef MP-WEIXIN
	// user.user_type = 1
	// #endif
	return new Promise((resolve, reject) => {
		if (loading) {
			uni.showLoading()
		}
		uni.request({
			url: requestUrl + url,
			...getType(data, method),
			success: res => {
				return resolve(res.data)
				if(res.data.errcode==99){
					console.log(1)
					// uni.showToast({
					// 	title:'登陆过期，请重新登陆',
					// 	icon:'none'
					// })
					// uni.navigateTo({
					// 	url:"/pages/login/login"
					// })
				}else if (res.errMsg === 'request:ok') {
					
				}
				reject(res.data)
			},
			fail: (err) => {
				if (loading) {
					uni.hideLoading()
				}
				reject(err)
			},
			// complete(res) {
			// 	if (res.statusCode === 401) {
			// 		// console.log(store)
			// 		// TODO 跳转登录页
			// 		store.dispatch('actionLoginOut');
			// 		uni.removeStorage({
			// 			key: 'USER_TOKEN',
			// 			success() {
			// 				uni.navigateTo({url: '/pages/login_method/login_method'});
			// 			}
			// 		});
			// 	}
			// }
		})
	});
}


export default function(url, method, data, loading) {
	return Request(url, method, data, loading)
}